#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <iostream>

void Usage(std::string proc)
{
    std::cout << proc << " IP port" << std::endl;
}
//./client IP port
int main(int args, char *argv[])
{
    if (args != 3)
    {
        Usage(argv[0]);
        return 1;
    }
    // 一.创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);

    // 客户端不需要自己bind,OS会自动帮用户bind

    // 二.使用服务
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);
    socklen_t len = sizeof(server);
    int quit = 5;
    while (quit)
    {
        // 发送信息
        std::string message;
        std::cin >> message;
        sendto(sock, message.c_str(), message.size(), 0, (sockaddr *)&server, len);

        // 接收客户端响应
        char buffer[2048];
        struct sockaddr_in tmp;
        socklen_t tmp_len = sizeof(tmp);
        recvfrom(sock, buffer, sizeof(buffer), 0, (sockaddr *)&tmp, &tmp_len);
        std::cout << "server #" << buffer << std::endl;
    }

    return 0;
}